package com.lysj.website.website.controller;

import cn.hutool.core.date.DateUtil;
import com.lysj.website.common.enumeration.EnumUtils;
import com.lysj.website.common.spring.base.BaseController;
import com.lysj.website.common.spring.jpa.ConditionUtil;
import com.lysj.website.common.validation.annotation.Valid;
import com.lysj.website.common.web.Resp;
import com.lysj.website.website.domain.TodayBrowseAmount;
import com.lysj.website.website.domain.Website;
import com.lysj.website.website.service.TodayBrowseAmountService;
import com.lysj.website.website.service.WebsiteService;
import com.lysj.website.website.utils.EasyPoiUtil;
import com.lysj.website.website.vo.WebsiteVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ Author ：drj.
 * @ Date  ：Created in 15:26 2019/10/25
 * @ Description:
 **/
@Slf4j
@RestController
@RequestMapping("/website/website")
public class WebsiteController extends BaseController<Website> {


    @Resource
    private WebsiteService websiteService;

    @Resource
    private TodayBrowseAmountService todayBrowseAmountService;

    @Override
    public WebsiteService getService() {
        return websiteService;
    }


    @Override
    public Resp save(@Valid Website entity) {
        log.info("提交官网信息 request ip:{}--------->>>>>>>>>>>" + request.getRemoteAddr());
        String ip = request.getRemoteAddr();
        entity.setIp(ip);
        Integer myAmount = websiteService.getRepository().countByIpAndCreateTimeBetween(ip,
                DateUtil.beginOfDay(new Date()).toJdkDate(), DateUtil.endOfDay(new Date()).toJdkDate());
        if (myAmount == 0) {
            //查询今日总的浏览数量
            TodayBrowseAmount todayBrowseAmount = todayBrowseAmountService.getRepository().findByCreateTimeBetween(DateUtil.beginOfMonth(new Date()).toJdkDate(), DateUtil.endOfMonth(new Date()).toJdkDate());
            todayBrowseAmount.setAmount(todayBrowseAmount.getAmount() + 1);
        }
        getService().save(entity);
        return new Resp().success("添加成功");
    }

    @GetMapping("/export")
    public void export(Website model, HttpServletResponse response) {
        Specification specification = ConditionUtil.createSpecification(model);
        List<Website> websiteList = getService().findAll(specification);
        List<WebsiteVo> websiteVoList = websiteList.stream()
                .map(e -> new WebsiteVo(e.getName(), e.getPhone(), e.getProvince(), e.getCity(), e.getCreateTime()))
                .collect(Collectors.toList());
        EasyPoiUtil.exportExcel(websiteVoList,"官网提交记录","官网提交记录",WebsiteVo.class,"官网提交记录.xls",response);
    }
}
